package com.imageflowpro.image_flow_pro.controller;

import com.imageflowpro.image_flow_pro.constant.JwtClaimsConstant;
import com.imageflowpro.image_flow_pro.context.BaseContext;
import com.imageflowpro.image_flow_pro.dto.LoginInitDTO;
import com.imageflowpro.image_flow_pro.dto.VerifyDTO;
import com.imageflowpro.image_flow_pro.dto.WXLoginDTO;
import com.imageflowpro.image_flow_pro.exception.LoginFailedException;
import com.imageflowpro.image_flow_pro.po.User;
import com.imageflowpro.image_flow_pro.properties.JwtProperties;
import com.imageflowpro.image_flow_pro.properties.WechatProperties;
import com.imageflowpro.image_flow_pro.result.Result;
import com.imageflowpro.image_flow_pro.service.IUserService;
import com.imageflowpro.image_flow_pro.utils.JwtUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private WechatProperties wechatProperties;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private IUserService iUserService;

    @GetMapping("/init")
    public Result<LoginInitDTO> loginInit(HttpSession session){
        // 生成随机的 state
        String state = UUID.randomUUID().toString();

        // 存入 session（或Redis），用于后续校验
        session.setAttribute("wechat_oauth_state", state);

        LoginInitDTO loginInitDTO = new LoginInitDTO();
        loginInitDTO.setScope(wechatProperties.getScope());
        loginInitDTO.setAppId(wechatProperties.getAppid());
        loginInitDTO.setRedirectUri(wechatProperties.getRedirectUri());
        loginInitDTO.setState(state);
        return Result.success(loginInitDTO);
    }



    @PostMapping("/user")
    public ResponseEntity<Map<String, Object>> wxLoginForUser(@RequestBody WXLoginDTO wxLoginDTO) {

        User user = iUserService.wxLoginUser(wxLoginDTO);
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("role", JwtClaimsConstant.USER_ROLE);

        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("token", token);
        result.put("user", user);

        return ResponseEntity.ok(result);
    }
//    @GetMapping("/user")
//    public ResponseEntity<String> handleWeChatCallbackUser(
//            @RequestParam("code") String code,
//            @RequestParam("state") String stateFromWeChat,
//            HttpSession session,
//            HttpServletResponse response) {
//
//        // 取出之前保存的 state
//        String savedState = (String) session.getAttribute("wechat_oauth_state");
//
//        if (savedState == null || !savedState.equals(stateFromWeChat)) {
//            throw new RuntimeException("state不匹配，可能存在CSRF攻击");
//        }
//
//        // 清除session中的state
//        session.removeAttribute("wechat_oauth_state");
//
//        User user=iUserService.wxLoginUser(code);
//        Map<String, Object> claims=new HashMap<>();
//        claims.put("id",user.getId());
//        claims.put("role",user.getRole());
//
//        // 生成自定义 token 并设置 HTTP-only cookie
//        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
//
//        Cookie cookie = new Cookie(jwtProperties.getUserTokenName(), token);
//        cookie.setHttpOnly(true);
////        cookie.setSecure(true); // 如果是HTTPS
//        cookie.setPath("/");
//        response.addCookie(cookie);
//
//        // 重定向到前端主页
//        return ResponseEntity.status(HttpStatus.FOUND)
//                .header(HttpHeaders.LOCATION, wechatProperties.getRedirectUiUserUri()+"/home")
//                .build();
//    }


    @PostMapping("/admin")
    public ResponseEntity<Map<String, Object>> wxLoginForAdmin(@RequestBody WXLoginDTO wxLoginDTO) {

        User admin=iUserService.wxLoginAdmin(wxLoginDTO);
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", admin.getId());
        claims.put("role",  JwtClaimsConstant.ADMIN_ROLE);

        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("token", token);
        result.put("admin", admin);

        return ResponseEntity.ok(result);
    }

    @GetMapping("/WXLogin/admin")
    public void handleWeChatCallbackAdmin(
            @RequestParam("code") String code,
            HttpServletResponse response) {

        WXLoginDTO wxLoginDTO = new WXLoginDTO();
        wxLoginDTO.setCode(code);
        User user=iUserService.wxLoginAdmin(wxLoginDTO);
        Map<String, Object> claims=new HashMap<>();
        claims.put("id",user.getId());
        claims.put("role",user.getRole());

        // 生成自定义 token 并设置 HTTP-only cookie
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getUserTtl(), claims);

        Cookie cookie = new Cookie(jwtProperties.getAdminTokenName(), token);
        cookie.setHttpOnly(true);
//        cookie.setSecure(true); // 如果是HTTPS
        cookie.setPath("/");
        response.addCookie(cookie);

        // 重定向到前端主页 要求返回值类型：ResponseEntity<String>
//        return ResponseEntity.status(HttpStatus.FOUND)
//                .header(HttpHeaders.LOCATION, wechatProperties.getRedirectUiAdminUri()+"/home")
//                .build();
    }

    @GetMapping("/user/checkLoginStatus")
    public Result<User> checkLoginStatusUser(){
        return Result.success(checkLoginStatusGetUser());
    }



    @GetMapping("/admin/checkLoginStatus")
    public Result<User> checkLoginStatusAdmin(){
        return Result.success(checkLoginStatusGetUser());
    }

    @PostMapping("/user/verify")
    public Result userVerify(@RequestBody VerifyDTO verifyDTO){
        iUserService.verify(verifyDTO.getCode());
        return Result.success();
    }
    @PostMapping("/admin/verify")
    public Result adminVerify(@RequestBody VerifyDTO verifyDTO){
        iUserService.verify(verifyDTO.getCode());
        return Result.success();
    }

    @GetMapping("/logout")
    public ResponseEntity<Void> logout(HttpServletResponse response) {
        // 清除用户的 Token Cookie
        Cookie userTokenCookie = new Cookie(jwtProperties.getUserTokenName(), null);
        userTokenCookie.setMaxAge(0); // 立即过期
        userTokenCookie.setPath("/"); // 全局路径
        userTokenCookie.setHttpOnly(true); // 安全性保持一致
        // userTokenCookie.setSecure(true); // 如果使用 HTTPS，请启用这行
        response.addCookie(userTokenCookie);

        // 清除管理员的 Token Cookie
        Cookie adminTokenCookie = new Cookie(jwtProperties.getAdminTokenName(), null);
        adminTokenCookie.setMaxAge(0); // 立即过期
        adminTokenCookie.setPath("/"); // 全局路径
        adminTokenCookie.setHttpOnly(true); // 安全性保持一致
        // adminTokenCookie.setSecure(true); // 如果使用 HTTPS，请启用这行
        response.addCookie(adminTokenCookie);

        // 返回204 No Content状态码表示请求成功但没有返回任何内容
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }



    //模拟用户登录接口
    @GetMapping("/user/simulateLogin")
    public ResponseEntity<String> simulateLoginUser(HttpServletResponse response) {
        // 创建一个模拟的用户信息或token等
        User user=iUserService.lambdaQuery()
                .eq(User::getOpenId,JwtClaimsConstant.OPEN_ID+"user")
                .one();
        if (user==null) {
            user = new User();
            user.setOpenId(JwtClaimsConstant.OPEN_ID+"user");
            user.setActive(true);
            user.setNickname("测试用户");
            user.setRole("CUSTOMER");
            iUserService.save(user);
        }
        Map<String, Object> claims=new HashMap<>();
        claims.put("id",user.getId());
        claims.put("role",user.getRole());


        // 生成自定义 token 并设置 HTTP-only cookie
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        Cookie cookie = new Cookie(jwtProperties.getUserTokenName(), token);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        response.addCookie(cookie);

        return ResponseEntity.ok("模拟登录成功");
    }


    //普通管理员模拟登录
    @GetMapping("/admin/simulateLogin")
    public ResponseEntity<String> simulateLoginAdmin(HttpServletResponse response) {
        // 创建一个模拟的用户信息或token等
        User user=iUserService.lambdaQuery()
                .eq(User::getOpenId,JwtClaimsConstant.OPEN_ID+"admin")
                .one();
        if (user==null) {
            user = new User();
            user.setOpenId(JwtClaimsConstant.OPEN_ID+"admin");
            user.setActive(false);
            user.setNickname("测试管理员");
            user.setRole("ADMIN");
            iUserService.save(user);
        }
        Map<String, Object> claims=new HashMap<>();
        claims.put("id",user.getId());
        claims.put("role",user.getRole());

        // 生成自定义 token 并设置 HTTP-only cookie
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getUserTtl(), claims);

        Cookie cookie = new Cookie(jwtProperties.getAdminTokenName(), token);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        response.addCookie(cookie);

        return ResponseEntity.ok("模拟登录成功");
    }

    @GetMapping("/superAdmin/simulateLogin")
    public ResponseEntity<String> simulateLoginSuperAdmin(HttpServletResponse response) {
        // 创建一个模拟的用户信息或token等
        User user=iUserService.lambdaQuery()
                .eq(User::getOpenId,JwtClaimsConstant.OPEN_ID+"superAdmin")
                .one();
        if (user==null) {
            user = new User();
            user.setOpenId(JwtClaimsConstant.OPEN_ID+"superAdmin");
            user.setActive(false);
            user.setNickname("测试超级管理员");
            user.setRole("SUPER_ADMIN");
            iUserService.save(user);
        }
        Map<String, Object> claims=new HashMap<>();
        claims.put("id",user.getId());
        claims.put("role",user.getRole());

        // 生成自定义 token 并设置 HTTP-only cookie
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getUserTtl(), claims);

        Cookie cookie = new Cookie(jwtProperties.getAdminTokenName(), token);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        response.addCookie(cookie);

        return ResponseEntity.ok("模拟登录成功");
    }


    private User checkLoginStatusGetUser() {
        try {
            Long id = BaseContext.getCurrentId();
            User user = iUserService.lambdaQuery()
                    .eq(User::getId, id)
                    .one();
            user.setOpenId(null);
            return user;
        } catch (Exception e) {
            throw new LoginFailedException("登录失败");
        }
    }
}
